import { ref, reactive } from 'vue';
import { defineStore } from 'pinia';
import request, { verify } from '@/Utils/request';
import { getObjValByKey } from '@/Utils/utils';

interface InfoType {
    objType: string;
    cacheId: string;
    expireSeconds: number;
    fixedExpireSeconds: boolean;
    id: number;
    userName: string;
    userPlatform: string;
    userImage: string;
    realName: string;
    mobile: string;
    currentBlocId: number;
    currentPlatform: string;
    clientId: string;
    currentPlatformPerRoles: string[];
    currentPlatformPerResList: CurrentPlatformPerResListItemType[];
    root: boolean;
    tourist: boolean;
}

interface CurrentPlatformPerResListItemType {
    resPlatform: string;
    resSystem: string;
    resCode: string;
    resUrl: string;
}

interface BlockListItemType {
    id: number;
    blocName: string;
    blocInviteCode?: any;
    blocArea?: any;
    blocAddress?: any;
    blocManagerUserid?: any;
    blocStatus?: any;
    saasVersionId?: any;
    saasVersionName?: any;
    saasVersionExpire?: any;
    saasVersionTime?: any;
    createTime?: any;
    createBy?: any;
    updateTime?: any;
    updateBy?: any;
}

/**
 * @author Elliot
 * @date 2023-04-18 17:53
 * @description 登录用户信息管理
 */
export const useUserStore = defineStore('userStore', () => {
    
    const blockId = ref<number | string>(0); // 当前选择的集团id

	const codes = ref<string[]>([]); // 权限编码列表

    const blocList = ref<BlockListItemType[]>([]);

    const user = reactive<InfoType>({
        "objType": "",
        "cacheId": "",
        "expireSeconds": 0,
        "fixedExpireSeconds": false,
        "id": 0,
        "userName": "",
        "userPlatform": "",
        "userImage": "",
        "realName": "",
        "mobile": "",
        "currentBlocId": 0,
        "currentPlatform": "",
        "clientId": "",
        "currentPlatformPerRoles": [],
        "currentPlatformPerResList": [],
        "root": true,
        "tourist": false
    });

    // 获取当前账号所属的集团
    const getBlocList = async () => {
        try {
            const list = await request({
                url: '/user/bloc-info/adminGetUserBlocs',
                query: {
                    id: (await getUserInfo()).id
                }
            });
            // console.log("list: ", list);
            blocList.value = list || [];
            return blocList.value;
        } catch (error) {
            
        }
    };

    // 保存集团id
    async function saveBlocId (blockIdVal = 0) {
        try {
            await request({
                url: '/user/auth/adminSwitchBloc',
                query: {
                    blocId: blockIdVal
                }
            });
            user.currentBlocId = blockIdVal;
            blockId.value = blockIdVal;
            await verify();
        } catch (error) {
            
        }
    };

    function saveInfo (info: InfoType) {
        // console.log('info: ', info)
        if (info) {
            user.objType = info.objType;
            user.cacheId = info.cacheId;
            user.expireSeconds = info.expireSeconds;
            user.fixedExpireSeconds = info.fixedExpireSeconds;
            user.id = info.id;
            user.userName = info.userName;
            user.userPlatform = info.userPlatform;
            user.userImage = info.userImage;
            user.realName = info.realName;
            user.mobile = info.mobile;
            user.currentBlocId = info.currentBlocId;
            user.currentPlatform = info.currentPlatform;
            user.clientId = info.clientId;
            user.currentPlatformPerRoles = info.currentPlatformPerRoles;
            user.currentPlatformPerResList = info.currentPlatformPerResList || [];
            user.root = info.root;
            user.tourist = info.tourist;
            setCode(info.currentPlatformPerResList || []);
            blockId.value = info.currentBlocId;
        }
    };

	// 保存权限编码
	function setCode (arr: CurrentPlatformPerResListItemType[]) {
        codes.value = arr.reduce((codeArr: string[], item) => {
            if (item.resCode) {
                codeArr.push(item.resCode);
            }
            return codeArr;
        }, []);
        // console.log('codes.value: ', codes.value);
	}

    /**
     * @Description 校验是否有权限
     * @param code 权限编码
     */
    async function hasPermission (code = '') {
        if (codes.value.length === 0) {
            await getUserInfo();
        }
        return codes.value.includes(code);
    }

    // 获取登录用户数据
    function getUserInfo () : Promise<InfoType> {
        return new Promise(async resolve => {
            if (user.id) {
                resolve(user);
            }
            getObjValByKey({
                obj: user,
                key: 'id',
                callback: async (res: any) => {
                    if (!res) {
                        await verify();
                    }
                    resolve(user);
                }
            });
        })
    }

	return { codes, blockId, user, blocList, saveInfo, hasPermission, saveBlocId, getUserInfo, getBlocList,  }
})
